package com.wzd.springmvc.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.wzd.springmvc.entity.UserEntity;
import com.wzd.springmvc.service.HelloService;

import common.login.RequestUtil;

@Controller
public class LoginController {
	
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private HelloService userService;
	
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>  login(HttpServletRequest request,HttpServletResponse response,@RequestBody String data) throws IOException{
 		System.out.println("执行了login方法！");
		Map<String,Object> result = new HashMap<String,Object>();
		System.out.println("参数data===="+data);
		Map<String,Object> map =new HashMap<String,Object>();
		Gson gson = new Gson();
        map = gson.fromJson(data, map.getClass());
		UserEntity user = userService.findUser(map.get("username").toString(), map.get("password").toString());
		if (user != null) {
			request.getSession().setAttribute("userId", user.getId());
			request.getSession().setAttribute("user", user);
			result.put("code", "1");
			result.put("mgs", "认证成功");
			//response.sendRedirect( "WEB-INFO/pages/main.do" ) ;
			//return new ModelAndView("forward:main.jsp");
			return result;
		} else {
			log.info("用户不存在");
			request.getSession().setAttribute("message", "用户名不存在，请重新登录");
			result.put("code", "0");
			result.put("mgs", "用户名不存在，请重新登录");
			return result;
		}
	}
}
